package classes
{
	import __AS3__.vec.Vector;
	
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	
	
	public class Matrix 
	{
		public var data:Array;

		public var width:int=0;		
		public var height:int=0;
		
		public function Matrix(w:int,h:int)
		{
			this.width	= w;
			this.height	= h;
			this.generateMatrix();
			
		}
		protected function generateMatrix():void{
			this.data = new Array(this.width);
			for(var i:int=0;i<this.width;i++){
				this.data[i] = new Array(this.height);
			}
		}
		
		public function slice(rect:Rectangle):classes.Matrix{
			if(rect.left<0) rect.left = 0;
			if(rect.top<0) rect.top = 0;
			var m:Matrix = new Matrix(rect.width,rect.height);
			for (var x:int = rect.left, mx:int=0; x< rect.right;x++,mx++){
				for (var y:int = rect.top, my:int=0 ;y<rect.bottom;y++, my++){
					m.data[mx][my] = this.data[x][y];
				}
			}
			return m;
		}

		//TODO: toBitmapData
		//TODO: fromBitmapData
		
		public static function fromBitmapData(btmData:BitmapData):classes.Matrix{
			var m:classes.Matrix =  new Matrix(btmData.width, btmData.height);
			for(var y:int=0;y<btmData.height;y++ ){
				for(var x:int=0;x<btmData.width;x++){
					var p:uint = btmData.getPixel(x,y);
					m.data[x][y] =  
						((p&0xff)  +  ((p>>8)&0xff) + ((p>>16)&0xff))/(0x2ff);
					if(m.data[x][y]>1 || m.data[x][y]<0) throw new Error("zła wartosc pixela");
				}
			}
			
			return m;
		}
		public function toBitmapData():BitmapData{
			var btmData:BitmapData = new BitmapData(this.width, this.height, false);
			
			for(var y:int=0;y<this.height;y++ ){
				for(var x:int=0;x<this.width;x++){
					var p:uint = Math.round(this.data[x][y]*255);
					var c:uint = p|(p<<8)|(p<<16);
					btmData.setPixel(x,y,c);
				}
			}			
			return btmData;
		}

	}
}